package org.syncsoft.overalt.communication.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.http.HttpEntity;
import org.syncsoft.overalt.communication.api.IConnectionEntityConverter;
import org.syncsoft.overalt.communication.exception.ConnectionException;

/**
 * abstract class to converter httpEntity to Collection
 * @author tptfc
 *
 */
public abstract class AbstractCollectionConnectionEntityConverter<T> implements IConnectionEntityConverter<Collection<T>> {
	private Collection<T> convertedResult;
	
	/*
	 * (non-Javadoc)
	 * @see org.syncsoft.overalt.communication.api.IConnectionEntityConverter#process(org.apache.http.HttpEntity)
	 */
	@Override
	public synchronized void process(HttpEntity entity) throws ConnectionException {
		setConvertedResult(null);
		
		if (entity != null) {
			try {
				InputStream stream = entity.getContent();
				setConvertedResult(new ArrayList<T>());
				int reader;
				
				while ((reader = stream.read()) >= 0) {
					getConvertedResult().add(convertReadedIntegerToType(reader));
				}
				
			} catch (IllegalStateException e) {
				throw new ConnectionException(e);
			} catch (IOException e) {
				throw new ConnectionException(e);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.syncsoft.overalt.communication.api.IConnectionEntityConverter#result()
	 */
	@Override
	public synchronized Collection<T> result() {
		return getConvertedResult();
	}
	
	/**
	 * @precondition reader > 0
	 * 
	 * @param readed
	 * @return converted value
	 */
	protected abstract T convertReadedIntegerToType(int reader);

	private Collection<T> getConvertedResult() {
		return convertedResult;
	}

	private void setConvertedResult(Collection<T> convertedResult) {
		this.convertedResult = convertedResult;
	}
}
